package cn.youyu.fm.controller;

import cn.youyu.fm.domain.Menu;
import cn.youyu.fm.domain.User;
import cn.youyu.fm.service.IMenuService;
import com.alibaba.fastjson.JSONArray;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: mayuanbao
 * @date: 2018-12-27 14:39
 * @description:
 */
@Controller
//@RequestMapping(value = "/home")
public class HomeController {
    @Resource(name = "menuService")
    private IMenuService menuService;

    @RequestMapping(value = "/index")
    public String index() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //获取所有菜单
        List<Menu> menus = menuService.getMenuByRoleId(user.getRoleId());
        System.out.println(menus);
        List<Menu> menuList = new ArrayList<>();
        //获取所有一级菜单
        for (Menu menu : menus) {
            System.out.println("****" + menu);
            //以及菜单parendId=0
            if (menu.getParentId() == 0) {
                menuList.add(menu);
            }
        }
        //为一级菜单设置子菜单，递归
        for (Menu menu : menuList) {
            menu.setChildMenus(getChild(menu.getId(), menus));
        }
        System.out.println(">>>>>menuList: " + JSONArray.toJSON(menuList));
        Session session = subject.getSession();
        session.setAttribute("menus", JSONArray.toJSON(menuList));
        session.setAttribute("username", user.getUsername());
        return "/home/index";
    }

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String welcome() {
        return "/home/welcome";
    }

    /**
     * @author: mayuanbao
     * @date: 2019-01-04 11:01
     * @param: [id, rootMenu]
     * @return: java.util.List<cn.youyu.fm.domain.Menu>
     * @description: 递归查找子菜单
     */

    private List<Menu> getChild(Integer id, List<Menu> rootMenu) {
        // 子菜单
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
                if (menu.getParentId() != 0 && menu.getParentId().equals(id)) {
                    childList.add(menu);
                }
        }
        // 把子菜单的子菜单再循环一遍
        for (Menu menu : childList) {// 没有url的子菜单还有子菜单
            if (menu.getUrl() == null) {
                // 递归
                menu.setChildMenus(getChild(menu.getId(), rootMenu));
            }
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
